package com.meilai.project.service.business.workbench.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.entity.business.workbench.CustomerEstimateRecord;
import com.meilai.project.entity.business.workbench.Year;
import com.meilai.project.entity.business.workbench.YearWeek;
import com.meilai.project.mapper.business.workbench.YearWeekMapper;
import com.meilai.project.service.business.workbench.CustomerEstimateRecordService;
import com.meilai.project.service.business.workbench.YearService;
import com.meilai.project.service.business.workbench.YearWeekService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 年度月份表 服务实现类
 * </p>
 *
 * @author haiYangXu
 * @since 2022-08-16
 */
@Service
public class YearWeekServiceImpl extends ServiceImpl<YearWeekMapper, YearWeek> implements YearWeekService {

    @Autowired
    private YearService yearService;
    @Autowired
    private CustomerEstimateRecordService customerEstimateRecordService;

    @Override
    public List<YearWeek> selectList(Long customer_id, Long record_id) {
        //暂定只查询本年的上下年度数据和下一年两年度的数据
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        List<Year> yearList = yearService.list(Wrappers.<Year>lambdaQuery().eq(Year::getYear, year).or().eq(Year::getYear, year + 1));
        List<Long> collect = yearList.stream().map(Year::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            collect.add(-1L);
        }
        List<YearWeek> list = this.list(Wrappers.<YearWeek>lambdaQuery().in(YearWeek::getYear_id, collect));
        // todo 修改为包含本周 增加逻辑 回显本周
        // 两种情况 开始时间再当天之后或者等于今天   开始时间小于今天 但是结束时间大于今天或者等于今天
        if (record_id == null) {// 不为null 的情况则是管理员修改预估记录
            list = list.stream().filter(item -> (item.getBegin_date() != null) && ((item.getBegin_date().isAfter(now) || item.getBegin_date().equals(now)) || (item.getBegin_date().isBefore(now) && (item.getEnd_date().isAfter(now) || item.getEnd_date().equals(now))))).collect(Collectors.toList());
        }
        // 过滤掉客户已经添加的数据
        List<CustomerEstimateRecord> data = customerEstimateRecordService.list(Wrappers.<CustomerEstimateRecord>lambdaQuery().eq(CustomerEstimateRecord::getCustomer_id, customer_id).ne(record_id != null, CustomerEstimateRecord::getId, record_id));
        if (CollectionUtils.isNotEmpty(data)) {
            List<Long> week_ids = data.stream().map(CustomerEstimateRecord::getWeek_id).distinct().collect(Collectors.toList());
            list = list.stream().filter(item -> !week_ids.contains(item.getId())).collect(Collectors.toList());
        }
        return list;
    }
}
